/**
 * 垂直排版文本省略（按列数限制显示）
 * @param {string} className - 目标元素的 class（不带点 .）
 * @param {number} [columns=5] - 最大列数
 * @param {number} [lineHeight=24] - 每列宽度（px）
 */
function mglEllipsis(className, columns, lineHeight) {
    const elements = document.querySelectorAll(`.${className}`);

    elements.forEach(el => {
        // 设置默认 line-height
        if (!el.style.lineHeight) {
            el.style.lineHeight = `${lineHeight}px`;
        }

        const style = getComputedStyle(el);
        const actualLineHeight = parseFloat(style.lineHeight);
        const maxWidth = actualLineHeight * columns;

        const originalText = el.innerText.trim();
        const words = originalText.split(/\s+/);
        let left = 0, right = words.length, result = originalText;

        while (left <= right) {
            const mid = Math.floor((left + right) / 2);
            let testText = words.slice(0, mid).join(" ");
            if (mid < words.length) testText += " •••";

            el.innerText = testText;

            if (el.scrollWidth > maxWidth) {
                right = mid - 1;
            } else {
                result = testText;
                left = mid + 1;
            }
        }

        el.innerText = result;
    });
}

/**
 * 加载字体并执行省略处理
 * @param {Object} options
 * @param {string} options.className - 元素类名
 * @param {string} options.fontName - 字体名
 * @param {number} [options.columns=2] - 列数限制
 * @param {number} [options.lineHeight=24] - 每列宽度（px）
 */
async function applyMongolianEllipsis({ className, fontName, columns = 2, lineHeight = 24 }) {
    await document.fonts.load(`1rem ${fontName}`).then(() => {
        mglEllipsis(className, columns, lineHeight);
    });
}
